package it.apiconsulting.wot.controller;


import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;

import it.apiconsulting.wot.model.FoodType;
import it.apiconsulting.wot.util.HibernateUtil;


public class FoodTypeManager extends HibernateUtil {
	
	public FoodType add(FoodType foodType) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(foodType);
		session.getTransaction().commit();
		return foodType;
	}
	public FoodType delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		FoodType foodType = (FoodType) session.load(FoodType.class, id);
		if(null != foodType) {
			session.delete(foodType);
		}
		session.getTransaction().commit();
		return foodType;
	}

	public FoodType getFoodTypeById(Long idType) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		FoodType foodType = null;
		try {
			
			Query query = session.createQuery("FROM FoodType WHERE id = "+idType);
			foodType = (FoodType)query.uniqueResult();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return foodType;
	}

	public List<FoodType> list() {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<FoodType> foodTypes = null;
		try {
			
			Query query = session.createQuery("from FoodType");
			foodTypes = (List<FoodType>)query.list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return foodTypes;
	}
}
